package top.buluoluo.ordersservice.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

public class OrderNoGenerator {
    // 时间格式化器
    private static final DateTimeFormatter TIMESTAMP_FORMATTER =
            DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    // 最后使用的时间戳
    private static volatile String lastTimestamp = "";

    // 序列号计数器
    private static final AtomicInteger sequence = new AtomicInteger(0);

    // 机器ID（可配置）
    private static final String MACHINE_ID = "01"; // 默认01，可通过配置修改

    // 最大序列号（9999）
    private static final int MAX_SEQUENCE = 9999;

    /**
     * 生成订单号
     */
    public static synchronized String generate() {
        // 获取当前时间戳
        String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMATTER);

        // 如果时间戳与上次相同，则增加序列号
        if (timestamp.equals(lastTimestamp)) {
            int currentSequence = sequence.incrementAndGet();

            // 如果序列号达到最大值，等待下一秒
            if (currentSequence > MAX_SEQUENCE) {
                waitNextSecond();
                timestamp = LocalDateTime.now().format(TIMESTAMP_FORMATTER);
                sequence.set(0);
                currentSequence = 0;
            }
        } else {
            // 时间戳变化，重置序列号
            sequence.set(0);
        }

        lastTimestamp = timestamp;

        // 格式化为4位序列号
        String sequenceStr = String.format("%04d", sequence.get());

        // 组合订单号
        return "ORD" + timestamp + MACHINE_ID + sequenceStr;
    }

    /**
     * 等待下一秒钟
     */
    private static void waitNextSecond() {
        long currentMillis = System.currentTimeMillis();
        long nextSecond = (currentMillis / 1000 + 1) * 1000;
        long sleepTime = nextSecond - currentMillis;

        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}